package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import pojo.Products;
import pojo.User;
import service.AdminProductsService;
import service.AdminUserService;
import service.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserLoginAndRegister {
    @RequestMapping("touLogin")
    public String initLogin(){return "userLogin";}
    @Autowired
    private UserService userService;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private AdminProductsService adminProductsService;
    @RequestMapping("/ulogin")
    public String login(Integer uid, String upwd, HttpSession session,Model model){
        List<User> userList=userService.log(uid,upwd);
        if(userList.size()!=0){
            List<Products> product=adminProductsService.sAP();
            model.addAttribute("product",product);
            session.setAttribute("userList",userList);
            return "searchAllProduct";
        }
        model.addAttribute("msg","用户名或密码错误！");
        return "userLogin";
    }
    @RequestMapping("/touRegister")
    public String initRegister(){return "userRegister";}
    @RequestMapping("/register")
    public String register(User user,Model model,HttpServletRequest request){
        String uname = request.getParameter("uname");
        String utel = request.getParameter("utel");
        String uemail = request.getParameter("uemail");
        List<User> userList = userService.checkName(uname);
        List<User> userList1 = userService.checkTel(utel);
        List<User> userList2 = userService.checkEmail(uemail);
        if (userList.size()!=0||userList1.size()!=0||userList2.size()!=0){
            model.addAttribute("msg","用户昵称或电话或邮箱重复！请重新输入！");
            return "userRegister";
        }
        else {
            int a= userService.reg(user);
            if(a>0){
                model.addAttribute("user",user);
                return "userLogin";
            }
        }
        model.addAttribute("msg","注册失败");
        return "userRegister";
    }
    @RequestMapping("/ulogOut")
    public String logOut(HttpSession session){
        session.invalidate();
        return "MainIndex";
    }
}
